package com.summer.LanQiao;

import java.util.Arrays;

public class _39 {
    static   int selectK(int[] arr,int left,int right,int k){
        int index = quickSort(arr,left,right);
        int count = k - 1;
        if (index==count) return arr[count];
        else if(index>count) return selectK(arr,left,index,k);
        else return selectK(arr,index,right,k);

    }
    public static int quickSort(int[] arr,int left,int right){
        int pivot = arr[(left + right) / 2];
        int l = left;
        int r = right;
        int temp = 0;
        int count = 0;
        int countL = 0;
        int countR = 0;
        while (l < r){
            while (arr[l] < pivot){
                l++;
                countL++;
            }
            while (arr[r] > pivot){
                r--;
                countR++;
            }
            if (l >= r) break;
            count++;
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            if (arr[l] == pivot) r--;
            if (arr[r] == pivot) l++;
        }
        if ((countL-countR)>0) return (left+right)/2+count;
        else if ((countL-countR)<0) return (left+right)/2-count;
        else return (left+right)/2;
    }
    static void qs(int[] arr,int left,int right){
        int pivot = arr[(left + right) / 2];
        int l = left;
        int r = right;
        int temp = 0;
        while (l < r){
            while (arr[l] < pivot) l++;
            while (arr[r] > pivot) r--;
            if (l >= r)break;
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            if (arr[l] == pivot) r--;
            if (arr[r] == pivot) l++;
        }
        if (l == r){
            l++;
            r--;
        }
        if (l < right) qs(arr,l,right);
        if (r > left) qs(arr,left,r);

        //

    }
    public static void main(String[] args) {
        int [] A ={9,4,2,8,1,5,3,8,9,4,6,5,7};
        System.out.println(selectK(A, 0, A.length - 1, 3));
        System.out.println(Arrays.toString(A));


    }
}
